package cn.edu.zjicm.wordsnet_d.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.activity.base.WordBaseActivity;
import cn.edu.zjicm.wordsnet_d.data.OneWord;
import cn.edu.zjicm.wordsnet_d.data.StaticData;
import cn.edu.zjicm.wordsnet_d.data.huanbo.HuanboListManager1;
import cn.edu.zjicm.wordsnet_d.datapersistent.FileManager;
import cn.edu.zjicm.wordsnet_d.db.WordFactory;
import cn.edu.zjicm.wordsnet_d.fragment.WordDetailForHuanboFragment;
import cn.edu.zjicm.wordsnet_d.media.VoicePlayer;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;
import cn.edu.zjicm.wordsnet_d.util.Utils;
import cn.edu.zjicm.wordsnet_d.view.MyDialog;

import com.umeng.analytics.MobclickAgent;

public class ExamHuanboActivity extends WordBaseActivity implements Runnable, OnClickListener {
	public static void startActivity(Context context) {
		Intent i = new Intent(context, ExamHuanboActivity.class);
		context.startActivity(i);
	}

	public static void startActivity(Context context, int familiarDegree) {
		Intent i = new Intent(context, ExamHuanboActivity.class);
		i.putExtra("familiar_degree", familiarDegree);
		context.startActivity(i);
	}

	private Button huanboAgainButton;
	private ViewFlipper displayFlipper, buttonFlipper;
	private LinearLayout fragmentContainer, huanboStateNotRepeat, huanboStateRepeating;
	private TextView endText, hintText, hintText1, huanboButton;
	private AudioManager audioManager;

	HuanboListManager1 huanboListManager;

	WordFactory wf = WordFactory.getInstance(this);

	private static int familiarDegree;
	private static List<OneWord> wordsList;
	boolean exit;
	boolean isPaused = false;

	Handler handler = new Handler();
	long wordStartTime;

	WordDetailForHuanboFragment mWordDetailFragment = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// 设定调整音量为媒体音量
		setVolumeControlStream(AudioManager.STREAM_MUSIC);

		initTitle();

		setBackButton(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				exitTest();
			}
		});

		audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

		familiarDegree = this.getIntent().getIntExtra("familiar_degree", -1);

		setContentView(R.layout.activity_exam_huanbo);

		displayFlipper = (ViewFlipper) findViewById(R.id.diplay_flipper);
		buttonFlipper = (ViewFlipper) findViewById(R.id.button_flipper);
		huanboButton = (TextView) findViewById(R.id.huanbo_button);
		huanboAgainButton = (Button) findViewById(R.id.huanbo_again_button);
		fragmentContainer = (LinearLayout) findViewById(R.id.word_detail_fragment_container);
		huanboStateNotRepeat = (LinearLayout) findViewById(R.id.huanbo_state_not_repeat);
		huanboStateRepeating = (LinearLayout) findViewById(R.id.huanbo_state_repeating);
		endText = (TextView) findViewById(R.id.end_text);
		hintText = (TextView) findViewById(R.id.test_hint);
		hintText1 = (TextView) findViewById(R.id.test_hint1);
		// huanboButton.setOnTouchListener(new
		// buttonListener());//触摸长按复读功能，暂时不用。
		huanboButton.setOnClickListener(this);
		huanboAgainButton.setOnClickListener(this);
		huanboStateNotRepeat.setOnClickListener(this);
		huanboStateRepeating.setOnClickListener(this);

		acquireWakeLock(); // 请求锁屏
		acquireAudioManager();

		startTest();
	}

	private void acquireAudioManager() {
		int result = audioManager.requestAudioFocus(onAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
		LogUtil.d("result=" + result);
	}

	private void initTitle() {
		setTitleBarStyle(WordBaseActivity.TITLE_BAR_STYLE_BACK_BUTTON);
		setTitleText("听音");
	}

	private void startTest() {
		mWordDetailFragment = null;
		fragmentContainer.removeAllViews();

		int num = initHuanboList(this);
		if (familiarDegree == -1)
			hintText.setText("听最近学过的单词共" + num + "个");
		else
			hintText.setText("需听音单词" + num + "个");
		if (num > 0) {
			List<OneWord> wordListForManager = new ArrayList<OneWord>();
			wordListForManager.addAll(wordsList);
			huanboListManager = new HuanboListManager1(wordListForManager, this);
			handler.post(this);
		} else {
			hintText1.setText("无需要听音的单词！");
			endText.setVisibility(View.GONE);
			displayFlipper.setDisplayedChild(1);
			huanboButton.setVisibility(View.GONE);
			huanboAgainButton.setVisibility(View.INVISIBLE);
		}
	}

	private void restartTest() {
		WordFactory wf = WordFactory.getInstance(ExamHuanboActivity.this);
		mWordDetailFragment = null;
		fragmentContainer.removeAllViews();

		for (int i = 0; i < wordsList.size(); i++) {
			wordsList.set(i, wf.getOneWordById(wordsList.get(i).getIndex_word_id()));
		}
		List<OneWord> wordListForManager = new ArrayList<OneWord>();
		wordListForManager.addAll(wordsList);
		huanboListManager.resetHuanboListManager1(wordListForManager);
		handler.post(this);
	}

	// 离开环播
	private void exitTest() {
		releaseWakeLock(); // 结束测试，截除锁屏
		exit = true;
		finish();
	}

	public static int initHuanboList(Context context) {
		// wordsList = wf.getLastForgetWords();
		if (familiarDegree == -1)
			wordsList = WordFactory.getInstance(context).getNewWordOrLastForgetWordsForHuanboLimit(1000);
		else if (familiarDegree == 0)
			wordsList = WordFactory.getInstance(context).getAllWordListForHuanboOfDegree(OneWord.DEGREE_UNFAMILIAR, 1000);
		else if (familiarDegree == 1)
			wordsList = WordFactory.getInstance(context).getAllWordListForHuanboOfDegree(OneWord.DEGREE_FAMILIAR, 1000);
		else if (familiarDegree == 2)
			wordsList = WordFactory.getInstance(context).getAllWordListForHuanboOfDegree(OneWord.SENSE_DEGREE_TOO_EASY, 1000);
		else if (familiarDegree == 3) {
			wordsList = WordFactory.getInstance(context).getDifficultyWordsLimit(0, StaticData.BufferSize);
		}

		// System.out.println("未过滤之前的list.size=" + wordsList.size());
		// for (int i = 0; i < wordsList.size(); i++) {
		// OneWord word = wordsList.get(i);
		// if (!FileManager.isVoiceFileExist(context, word)) {
		// wordsList.remove(i);
		// i--;
		// }
		// }
		// System.out.println("过滤之后的list.size="+wordsList.size());
		// if(wordsList.size() > 20)
		// wordsList = wordsList.subList(0, 20);
		return wordsList.size();
	}

	public void run() {
		if (exit)
			return;

		if (!huanboListManager.repeating) {
			huanboListManager.changeCurWordVoiceFamiliarDegree(-1);
		}
		if (huanboListManager.next() == false) {
			huanboButton.setVisibility(View.GONE);
			// buttonFlipper.setDisplayedChild(1);
			if (familiarDegree == 0)
				endText.setText("已完成生词的听音！");
			else if (familiarDegree == 1)
				endText.setText("已完成熟词的听音！");
			displayFlipper.setDisplayedChild(1);
			// buttonFlipper.setDisplayedChild(1);
			return;
		}
		wordStartTime = java.lang.System.currentTimeMillis();
		if (huanboListManager.repeating) {
			huanboListManager.pre();
			huanboListManager.addCurWordRepeatingCount();
		}
		VoicePlayer.getInstance(this).play(huanboListManager.getCurWord());
		setCurWord();
		// showCurWord(huanboListManager.repeating);

		handler.postDelayed(this, HuanboListManager1.INTERVAL_PER_WORD);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean consumed = false;
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			exitTest();
		}
		return consumed;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == huanboButton) {
			huanboListManager.repeating = !huanboListManager.repeating;
			if (huanboListManager.repeating) {
				// 在单词播放1秒钟内点击复读，将复读上一单词
				long curTime = java.lang.System.currentTimeMillis();
				if (curTime - wordStartTime <= HuanboListManager1.INTERVAL_DISPLAY_AFTER_VOCIE_PLAY) {
					huanboListManager.pre();
					setCurWord();
				}
				huanboStateRepeating.setVisibility(View.VISIBLE);
				huanboStateNotRepeat.setVisibility(View.GONE);

				// displayFlipper.setDisplayedChild(1);
				// huanboRepeatButton.setText("取消复读");
				// huanboRepeatButton.setBackgroundResource(R.drawable.gray_button_selector);
				// huanboRepeatButton.setTextColor(getResources().getColor(R.color.black));
			} else {

				huanboStateRepeating.setVisibility(View.GONE);
				huanboStateNotRepeat.setVisibility(View.VISIBLE);
				// displayFlipper.setDisplayedChild(0);
				// huanboRepeatButton.setText("复读");
				// huanboRepeatButton.setBackgroundResource(R.drawable.green_button_selector);
				// huanboRepeatButton.setTextColor(getResources().getColor(R.color.white));
				huanboListManager.onEndRepeatOneWord();
			}
		} else if (v == huanboAgainButton) {
			// buttonFlipper.setDisplayedChild(0);
			displayFlipper.setDisplayedChild(0);
			huanboButton.setVisibility(View.VISIBLE);
			restartTest();
		}
	}

	private void setCurWord() {
		// Toast.makeText(this, huanboListManager.getCurWord().getLemma(),
		// Toast.LENGTH_LONG).show();
		// Log.e("voice", huanboListManager.getCurWord().getLemma());
		// displayFlipper.setDisplayedChild(1);
		if (mWordDetailFragment == null) {
			mWordDetailFragment = new WordDetailForHuanboFragment(huanboListManager.getCurWord());
			FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
			ft.add(R.id.word_detail_fragment_container, mWordDetailFragment);
			ft.commit();
		} else
			mWordDetailFragment.initViewForNewWord(huanboListManager.getCurWord());
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
		if (isPaused) {
			showPauseDialog();
		}
	}

	public void showPauseDialog() {
		View view = LayoutInflater.from(this).inflate(R.layout.view_pause_dialog, null);
		RelativeLayout pause = (RelativeLayout) view.findViewById(R.id.continue_btn);
		final MyDialog dialog = new MyDialog(this, view, R.style.mydialog, false);
		pause.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				dialog.cancel();
			}
		});
		dialog.setCanceledOnTouchOutside(true);
		dialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface arg0) {
				isPaused = false;
				handler.post(ExamHuanboActivity.this);
			}
		});
		dialog.show();
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (Utils.getScreenState(this)) {
			// exitTest();
		}
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		audioManager.abandonAudioFocus(onAudioFocusChangeListener);
	}

	WakeLock wakeLock = null;

	// 休眠时保持屏幕一直亮着，但降低亮度
	private void acquireWakeLock() {
		if (wakeLock == null) {
			PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
			wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, this.getClass().getCanonicalName());
			wakeLock.acquire();
		}
	}

	// 释放锁屏
	private void releaseWakeLock() {
		if (wakeLock != null && wakeLock.isHeld()) {
			wakeLock.release();
			wakeLock = null;
		}
	}

	OnAudioFocusChangeListener onAudioFocusChangeListener = new OnAudioFocusChangeListener() {

		@Override
		public void onAudioFocusChange(int focusChange) {
			LogUtil.d("调用onAudioFocusChange");
			if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) { // 暂时失去AudioFocus
				handler.removeCallbacks(ExamHuanboActivity.this);
				VoicePlayer.getInstance(ExamHuanboActivity.this).releaseMediaPlayer();
				isPaused = true;

			} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
				handler.removeCallbacks(ExamHuanboActivity.this);
				VoicePlayer.getInstance(ExamHuanboActivity.this).releaseMediaPlayer();
				isPaused = true;

			} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) { // 获得AudioFocus
			}
		}
	};
}
